package com.tjshop.android.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;

import com.example.qr_codescan.MipcaActivityCapture;
import com.tjshop.android.BannerActivity;
import com.tjshop.android.GoodsListActivity;
import com.tjshop.android.HomeCategoryGridView;
import com.tjshop.android.MainActivity;
import com.tjshop.android.R;
import com.tjshop.android.GoodsDetailActivity;
import com.tjshop.android.SearchActivity;
import com.tjshop.android.adapter.CategoryAdapter;
import com.tjshop.android.adapter.NewGoodsAdapter;
import com.tjshop.android.constants.UrlConfigs;
import com.tjshop.android.db.CacheBanner;
import com.tjshop.android.db.CacheHomeCategory;
import com.tjshop.android.db.CacheNewGoods;
import com.tjshop.android.model.tj.HomeData;
import com.tjshop.android.model.tj.json.Banner;
import com.tjshop.android.model.tj.json.Goods;
import com.tjshop.android.model.tj.json.HomeCategory;
import com.tjshop.android.util.HttpUtil;
import com.tjshop.android.util.ImageLoaderUtils;
import com.tjshop.android.util.ObjectDBUtils;
import com.tjshop.android.view.IndicatorView;
import com.tjshop.android.view.InsideListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class FragmentHome extends Fragment implements Handler.Callback {

	public HomeData homeData = new HomeData();
	private final static int SCANNIN_GREQUEST_CODE = 1;
	private Context mContext;
	private Handler handler;
	private HomeCategory homeCategory = new HomeCategory();
	ViewPager mBannerSubject;
	IndicatorView indicatorView;
	HomeCategoryGridView gridView;
	private EditText search;
	InsideListView listView;

	private View homeView;

	public FragmentHome() {
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		boolean userVisibleHint = getUserVisibleHint();
		Log.w(FragmentHome.class.getSimpleName(),
				"onCreate - userVisibleHint: " + userVisibleHint);
		mContext = this.getActivity();
		handler = new Handler(this);
		getHomeBanner();
		getHomeCategory();
		getNewGoods();
		if(MainActivity.mHandler!=null)
		MainActivity.mHandler.sendEmptyMessageDelayed(1, 3000);
	}

	private void getNewGoods() {
		CacheNewGoods caches = new ObjectDBUtils<CacheNewGoods>().readObject(
				getActivity(), CacheNewGoods.class);
		if (caches != null) {
			homeData.setNewGoodsList(caches.getGoods());
		}
		new Thread(new Runnable() {
			@Override
			public void run() {
				Message message = new Message();
				String ret = HttpUtil.sendPost(UrlConfigs.URL_NEW_GOODS, "");
				if (!ret.equals("")) {
					try {
						JSONObject jsonObject = new JSONObject(ret);
						if (jsonObject.getInt("r") == 0) {
							JSONArray array = jsonObject.getJSONArray("s");
							homeData.setNewGoodsList(new ArrayList<Goods>());
							for (int i = 0; i < array.length(); i++) {
								Goods g = new Goods();
								g.parse(array.getJSONObject(i));
								homeData.addNewGoods(g);
							}
						}
						CacheNewGoods model = new CacheNewGoods();
						model.setGoods(homeData.getCouponList());
						new ObjectDBUtils<CacheNewGoods>().saveObject(
								getActivity(), model);
						message.what = 0;
						handler.sendMessage(message);
					} catch (JSONException e) {
						e.printStackTrace();
					}

				}

			}
		}).start();

	}

	private void getHomeBanner() {
		CacheBanner caches = new ObjectDBUtils<CacheBanner>().readObject(
				getActivity(), CacheBanner.class);
		if (caches != null) {
			homeData.setBanners(caches.getBanners());
		}
		new Thread(new Runnable() {
			@Override
			public void run() {
				Message message = new Message();
				String ret = HttpUtil.sendPost(UrlConfigs.URL_HOME_BANNER, "");
				if (!ret.equals("")) {
					try {
						JSONObject jsonObject = new JSONObject(ret);
						if (jsonObject.getInt("r") == 0) {
							JSONArray array = jsonObject.getJSONArray("s");
							homeData.setBanners(new ArrayList<Banner>());
							for (int i = 0; i < array.length(); i++) {
								Banner banner = new Banner();
								banner.parse(array.getJSONObject(i));
								homeData.addBanner(banner);
							}
						}
						CacheBanner model = new CacheBanner();
						model.setBanners(homeData.getBannerList());
						new ObjectDBUtils<CacheBanner>().saveObject(
								getActivity(), model);
						message.what = 0;
						handler.sendMessage(message);
					} catch (JSONException e) {
						e.printStackTrace();
					}

				}

			}
		}).start();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = LayoutInflater.from(getActivity()).inflate(
				R.layout.activity_main_fragment_home, null);
		homeView = v;
		initHomeList(homeView);
		return v;
	}

	/**
	 * 初始化HomeList。
	 * 
	 * @param container
	 */
	private void initHomeList(final View container) {
		mBannerSubject = (ViewPager) container.findViewById(R.id.banner);
		indicatorView = (IndicatorView) container
				.findViewById(R.id.indicatorView);
		gridView = (HomeCategoryGridView) container
				.findViewById(R.id.fragment_home_categories);
		listView = (InsideListView) container
				.findViewById(R.id.listview_fragment_home_shop_list);
		
		search = (EditText) container.findViewById(R.id.fragment_home_title_bar_search);
		
		search.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				startActivity(new Intent(getActivity(), SearchActivity.class));
			}
		});
		
		container.findViewById(R.id.common_title_bar_right_icon).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(getActivity(), MipcaActivityCapture.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			}
		});
		// 初始化banner
		initBannerSubject();
		// 初始化分类
		initCategories();
		// 初始化最新上架
		initNewGoods();

		// PinnedSectionListView list = (PinnedSectionListView) container
		// .findViewById(R.id.fragment_home_guest_list);
		// list.setShadowVisible(false);
		// list.setAdapter(new HomeListAdapter(mContext,homeData));
		// list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
		// @Override
		// public void onItemClick(AdapterView<?> parent, View view,
		// int position, long id) {
		// Log.w(FragmentHome.class.getSimpleName(), "position: "
		// + position);
		//
		// if (position >= 4) {
		// startActivity(new Intent(getActivity(),
		// CouponDetailActivity.class));
		// }
		// }
		// });

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onStart() {
		super.onStart();

		boolean userVisibleHint = getUserVisibleHint();
		Log.w(FragmentHome.class.getSimpleName(), "onStart - userVisibleHint: "
				+ userVisibleHint);
	}

	@Override
	public void onStop() {
		super.onStop();

		boolean userVisibleHint = getUserVisibleHint();
		Log.w(FragmentHome.class.getSimpleName(), "onStop - userVisibleHint: "
				+ userVisibleHint);
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();

		boolean userVisibleHint = getUserVisibleHint();
		Log.w(FragmentHome.class.getSimpleName(),
				"onDestroyView - userVisibleHint: " + userVisibleHint);
	}

	@Override
	public void onPause() {
		super.onPause();

		boolean userVisibleHint = getUserVisibleHint();
		Log.w(FragmentHome.class.getSimpleName(), "onPause - userVisibleHint: "
				+ userVisibleHint);
	}

	@Override
	public void onResume() {
		super.onResume();

		boolean userVisibleHint = getUserVisibleHint();
		Log.w(FragmentHome.class.getSimpleName(),
				"onResume - userVisibleHint: " + userVisibleHint);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	void getHomeCategory() {
		CacheHomeCategory caches = new ObjectDBUtils<CacheHomeCategory>()
				.readObject(getActivity(), CacheHomeCategory.class);
		if (caches != null) {
			homeData.setCategoryList(caches.getItems());
		}

		new Thread(new Runnable() {
			@Override
			public void run() {
				Message message = new Message();
				String ret = HttpUtil.sendPost(UrlConfigs.URL_HOMECATEGORY, "");
				if (!ret.equals("")) {
					try {
						JSONObject obj = new JSONObject(ret);
						if (obj.getInt("r") == 0) {
							JSONArray array = obj.getJSONArray("s");
							homeCategory = new HomeCategory();
							homeCategory.parse(array);
							homeData.setCategoryList(homeCategory);

							CacheHomeCategory model = new CacheHomeCategory();
							model.setItems(homeCategory);
							new ObjectDBUtils<CacheHomeCategory>().saveObject(
									getActivity(), model);

							message.what = 0;
							handler.sendMessage(message);
						} else {

						}

					} catch (JSONException e) {
						e.printStackTrace();
					}

				}

			}
		}).start();
	}

	@Override
	public boolean handleMessage(Message message) {
		switch (message.what) {
		case 0:
			Toast.makeText(mContext, "获取主页分类成功！", Toast.LENGTH_SHORT).show();
			initHomeList(homeView);
			break;
		case 1:
			Toast.makeText(mContext, "获取主页分类失败!", Toast.LENGTH_SHORT).show();
			break;
		case 2:
			Toast.makeText(mContext, "获取城市信息成功！", Toast.LENGTH_SHORT).show();
			break;
		case 3:
			Toast.makeText(mContext, "获取城市信息失败!", Toast.LENGTH_SHORT).show();
			break;
		default:
			break;
		}
		return false;
	}

	/**
	 * 初始化BannerSubject。
	 * 
	 * @param container
	 */
	/**
	 * 初始化BannerSubject。
	 * 
	 * @param container
	 */
	HashMap<Integer, ImageView> mBannerImageViews;
	List<String> mBannerImages;
	private Handler bannerHandler;

	private void initBannerSubject() {
		bannerHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				int index = mBannerSubject.getCurrentItem();

				if (index < mBannerImages.size() - 1) {
					index++;
				} else {
					index = 0;
				}
				mBannerSubject.setCurrentItem(index);

				sendEmptyMessageDelayed(1, 10000);
			}
		};
		// 显示的图片
		mBannerImages = new ArrayList<String>();
		mBannerImageViews = new HashMap<Integer, ImageView>();
		for (int i = 0; i < homeData.getBannerList().size(); i++) {
			mBannerImages.add(homeData.getBannerList().get(i).getPath());

			ImageView view = new ImageView(getActivity());
			view.setScaleType(ScaleType.FIT_XY);
			mBannerImageViews.put(i, view);

		}
		mBannerSubject.setAdapter(adapter);
		mBannerSubject.setOnPageChangeListener(MyOnPageChangeListener);

		indicatorView.setPointNum(mBannerImages.size());
		indicatorView.setSelectedIndex(0);
		indicatorView.postInvalidate();

		bannerHandler.sendEmptyMessageDelayed(1, 10000);
		// mBannerSubject.setOnItemClickListener(new OnItemClickListener() {
		//
		// @Override
		// public void onClick(int index, View childview) {
		// Intent intent = new Intent(context, BannerActivity.class);
		// Bundle b = new Bundle();
		// b.putString("url",
		// homeData.getBannerList().get(index).getContentUrl());
		// intent.putExtras(b);
		// context.startActivity(intent);
		// }
		// });
	}

	OnPageChangeListener MyOnPageChangeListener = new OnPageChangeListener() {
		@Override
		public void onPageScrollStateChanged(int arg0) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			indicatorView.setSelectedIndex(arg0);
			indicatorView.postInvalidate();
		}

		@Override
		public void onPageSelected(int arg0) {
			indicatorView.setSelectedIndex(arg0);
			indicatorView.postInvalidate();
		}
	};
	PagerAdapter adapter = new PagerAdapter() {

		@Override
		public int getCount() {
			return mBannerImages.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void destroyItem(View container, int position, Object object) {
		}

		/**
		 * 载入图片进去，用当前的position 除以 图片数组长度取余数是关键
		 */
		@Override
		public Object instantiateItem(View container, final int position) {
			// System.out.println("装载"+position);
			ImageView v = mBannerImageViews.get(position);
			if (v.getTag() == null || !v.getTag().equals("hasParent")) {
				((ViewPager) container).addView(v, 0);
				v.setTag("hasParent");
				v.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						if (mBannerImageViews.get(position).equals(arg0)) {
							Intent intent = new Intent(getActivity(),
									BannerActivity.class);
							Bundle b = new Bundle();
							b.putString("title",
									homeData.getBannerList().get(position)
											.getAdName());
							b.putString("url",
									homeData.getBannerList().get(position)
											.getAdlink());
							intent.putExtras(b);
							getActivity().startActivity(intent);
						}
					}
				});
				ImageLoaderUtils.getInstance(getActivity()).displayImage(
						mBannerImages.get(position), v);
			}
			return v;
		}
	};

	/**
	 * 初始化分类。
	 * 
	 * @param container
	 */
	private void initCategories() {

		CategoryAdapter adapter = new CategoryAdapter(mContext,
				homeData.getCategoryList(), LayoutInflater.from(getActivity()));
		// 获得GridView实例并进行设置
		gridView.setAdapter(adapter); // 为GridView设置数据源
		gridView.setOnItemClickListener(new ItemClickListener());
	}

	// 当AdapterView被单击(触摸屏或者键盘)，则返回的Item单击事件
	class ItemClickListener implements AdapterView.OnItemClickListener {
		public void onItemClick(AdapterView<?> arg0,// The AdapterView where the
													// click happened
				View arg1,// The view within the AdapterView that was clicked
				int arg2,// The position of the view in the adapter
				long arg3// The row id of the item that was clicked
		) {
//			Toast.makeText(getActivity(), "功能开发中", Toast.LENGTH_SHORT).show();
			if(arg2 == 6 || arg2 == 7){
				Toast.makeText(getActivity(), "功能开发中", Toast.LENGTH_SHORT).show();
				return;
			}
			Bundle b = new Bundle();
			b.putString("gId", homeData.getCategoryList()
					.getItems().get(arg2).getCat_id());
			b.putString("name", homeData.getCategoryList()
					.getItems().get(arg2).getCat_name());
			Intent intent = new Intent();
			intent.putExtras(b);
			intent.setClass(mContext, GoodsListActivity.class);
			mContext.startActivity(intent);
		}
	}

	/**
	 * 初始化猜你喜欢。
	 * 
	 * @param container
	 */
	private void initNewGoods() {

		NewGoodsAdapter adapter = new NewGoodsAdapter(mContext,
				homeData.getCouponList(), LayoutInflater.from(getActivity()));
		// 获得GridView实例并进行设置
		listView.setAdapter(adapter); // 为GridView设置数据源
		listView.setOnItemClickListener(new ListViewItemClickListener());
	}

	// 当AdapterView被单击(触摸屏或者键盘)，则返回的Item单击事件
	class ListViewItemClickListener implements AdapterView.OnItemClickListener {
		public void onItemClick(AdapterView<?> arg0,// The AdapterView where the
													// click happened
				View arg1,// The view within the AdapterView that was clicked
				int arg2,// The position of the view in the adapter
				long arg3// The row id of the item that was clicked
		) {
			// GlobeVars.mTabHost.setCurrentTab(1);
			// GlobeVars.CouponCategory = homeCouponList.get(arg2).getTitle();
			Intent intent = new Intent(getActivity(), GoodsDetailActivity.class);
			intent.putExtra("gId", homeData.getCouponList().get(arg2)
					.getGoods_id());
			getActivity().startActivity(intent);
//			Toast.makeText(getActivity(), "功能开发中", Toast.LENGTH_SHORT).show();

		}
	}
}
